package com.easipass.exangeservice.ucx;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.easipass.exangeservice.MsgListener;
import com.easipass.exangeservice.monitor.UnicFileMsgMonitor;
import com.easipass.exangeservice.msg.FileMsg;
import com.easipass.exangeservice.msg.Msg;
import com.easipass.exangeservice.msg.TextFileMsg;
import com.easipass.exangeservice.ucx.UcxService;
import com.easipass.exangeservice.utils.EncodingDetector;
import com.easipass.unifiedconfig.ConfigManager;
import com.easipass.unifiedconfig.DefaultConfigManager;
import com.easipass.unifiedconfig.InsufficientPrivillageException;
import com.easipass.unifiedconfig.NotFoundException;
import com.easipass.unifiedconfig.Parameter;
import com.easipass.unifiedconfig.Session;
import com.easipass.unifiedconfig.UCI;
import com.easipass.unifiedconfig.Parameter.AccessLevel;
import com.easipass.unifiedconfig.core.ConfigDomain;
import com.easipass.unifiedconfig.script.ScriptExecuter;
import com.easipass.unifiedconfig.unic.UnicConfigDomainFactory;

/**
 * 
 * @version $Id$
 * @author itea
 * @date 2010-2-8
 */
public class UcxService implements MsgListener {

	protected final Log log = LogFactory.getLog(this.getClass());
	
	private ConfigManager configManager;
	
	
	public void setConfigManager(ConfigManager configManager) {
		this.configManager = configManager;
	}

	public UcxService() {
		
	}
	
	public void onMsg(Msg msg) {
		if(msg instanceof FileMsg) {
			FileMsg m = (FileMsg)msg;
			if(!m.getFileName().endsWith(".script")) return;

			log.info(m.getPath());
			
			Reader reader = null;
			Writer writer = null;
			
			try {
					String encoding = EncodingDetector.getCharset(m.getFile()).name();
					
					TextFileMsg inMsg = new TextFileMsg(m, encoding);
					TextFileMsg outMsg = new TextFileMsg(new File(inMsg.getPath()+ ".result"), encoding);
					
					reader = inMsg.openReader();
					writer = outMsg.openWriter();
					
					ScriptExecuter exec = configManager.newScriptExecuter();
					exec.setWriter(writer);
					exec.eval(reader);
					
			} catch (Exception e) {
				if(writer != null)
					try {
						writer.write("[ERROR]"+ e.toString());
					} catch (IOException e1) {
						log.error(e1, e1);
					}
				else
					log.info(e);
			} finally {
				if(reader != null)
					try {
						reader.close();
					} catch (IOException e) {
						log.error(e, e);
					}
				if(writer != null)
					try {
						writer.close();
					} catch (IOException e) {
						log.error(e, e);
					}
				m.moveTo(new File(m.getPath()+".done"));
			}
		}
	}
	

	public static void main(String[] args) {
		UnicFileMsgMonitor m = new UnicFileMsgMonitor(new UCI("unic:exangeservice[unicfsmsgmonitor]"));
		
		Map<String, String> option = new HashMap<String, String>();
		option.put("domain", "unic");
		option.put("unic.rootpassword", "root");
		ConfigDomain repo = new UnicConfigDomainFactory().getConfigDomain(option);
		DefaultConfigManager cm = new DefaultConfigManager();
		cm.registerRepository(repo, repo.authenticate("root", "root"));
		
		Session session = cm.newSession();
		Parameter p;
		try {
			session.authenticate("unic", "root", "root");
			p = new Parameter("unic:exangeservice[unicfsmsgmonitor]/monitor_path");
			p.insertValues("E:\\a_work\\0220");
			p.setAccessLevel(AccessLevel.PUBLIC);
			session.setParameter(p);
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InsufficientPrivillageException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		m.setConfigManager(cm);
		/*m.setMsgListener(new MsgListener() {

			@Override
			public void onMsg(Msg msg) {
				System.out.printf(" %s %s", msg.getAttribute(Msg.ATTR_SENDER), ((FileMsg)msg).getSize());
			}
			
		});*/
		UcxService ml = new UcxService();
		ml.setConfigManager(cm);
		m.setMsgListener(ml);
		m.setPeriod(10000);
		m.start();
	}

}
